package com.robot.config;

import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.robot.service.langchain.ApiQueryService;
import com.robot.service.langchain.ConversationService;

import java.time.Duration;

/**
 * LangChain4j 配置类
 */
@Configuration
public class LangChainConfig {

    @Value("${llm.api.url}")
    private String apiUrl;
    
    @Value("${llm.api.key}")
    private String apiKey;
    
    @Value("${llm.api.model}")
    private String modelName;
    
    @Value("${llm.api.timeout:60000}")
    private int timeoutMillis;

    @Value("${llm.memory.max-messages:10}")
    private int maxMessages;
    

    /**
     * 对象映射器用于JSON处理
     */
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
    
    /**
     * 配置语言模型
     */
    @Bean
    @Primary
    public ChatLanguageModel chatLanguageModel() {
        return OpenAiChatModel.builder()
                .baseUrl(apiUrl)
                .apiKey(apiKey)
                .modelName(modelName)
                .timeout(Duration.ofMillis(timeoutMillis))
                .build();
    }
    
    /**
     * 配置聊天记忆
     */
    @Bean
    public ChatMemory chatMemory() {
        return MessageWindowChatMemory.builder()
                .maxMessages(maxMessages)
                .build();
    }
    
    /**
     * API查询服务
     */
    @Bean
    public ApiQueryService apiQueryService(ChatLanguageModel chatLanguageModel) {
        return AiServices.builder(ApiQueryService.class)
                .chatLanguageModel(chatLanguageModel)
                .build();
    }
    
    /**
     * 会话服务，支持上下文记忆
     */
    @Bean
    public ConversationService conversationService(ChatLanguageModel chatLanguageModel, ChatMemory chatMemory) {
        return AiServices.builder(ConversationService.class)
                .chatLanguageModel(chatLanguageModel)
                .chatMemory(chatMemory)
                .build();
    }
} 